package com.lanou3g.musicenjoy.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.adapter.RecomGrideAdapter;
import com.lanou3g.musicenjoy.adapter.RecomListAdapter;
import com.lanou3g.musicenjoy.adapter.RecomNewAdapter;
import com.lanou3g.musicenjoy.adapter.ViewPagerAdapter;
import com.lanou3g.musicenjoy.entity.NewGride;
import com.lanou3g.musicenjoy.entity.NewImageView;
import com.lanou3g.musicenjoy.entity.NewSongList;
import com.lanou3g.musicenjoy.entity.NewSongListEntity;
import com.lanou3g.musicenjoy.entity.PlayHotMusic;
import com.lanou3g.musicenjoy.entity.PlayMusicEntity;
import com.lanou3g.musicenjoy.entity.RecomGride;
import com.lanou3g.musicenjoy.entity.RecomList;
import com.lanou3g.musicenjoy.entity.Recommendation;
import com.lanou3g.musicenjoy.eventbus.MyEvent;
import com.lanou3g.musicenjoy.utils.NoScrollGridView;
import com.lanou3g.musicenjoy.utils.NoScrollListView;
import com.lanou3g.musicenjoy.volley.VolleySingleton;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/20.
 */
public class RecommendationFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener, AdapterView.OnItemClickListener {
    private List<Recommendation.PicEntity> datas;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;//轮播适配器
    private RequestQueue queue;
    private LinearLayout linearLayout;
    private View view;
    private Handler handler;
    private Runnable runnable;
    private boolean flag = false;
    private static final int Time = 5000;//轮播时间间隔
    private List<RecomGride.ContentEntity.ListEntity> data;
    private RecomGrideAdapter grideAdapter;
    private NoScrollGridView gridView;
    private TextView recomTextView;
    private List<RecomList.ContentEntity.SongListEntity> dataone;
    private RecomListAdapter listAdapter;
    private NoScrollListView listView;
    private List<PlayMusicEntity> play;
    private ImageView newRecomGrideView;
    private TextView newRecomTextView;
    private TextView newRecomText;
    private NewImageView.CollectionEntity dataI;
    private RecomNewAdapter newAdapter;
    private List<NewGride.PlazeAlbumListEntity.RMEntity.AlbumListEntity.ListEntity> dataN;
    private NoScrollGridView newNoScrollGridView;
    private TextView newMore;
    private NewLeftFragment leftFragment;
    private NewRightFragment rightFragment;
    private Context mContext;
    private List<PlayHotMusic.SonginfoEntity> newSongList;
    private List<PlayMusicEntity> dataP = new ArrayList<>();
    private int clickPosition;//记录当前点击的位置
    private int numOfData;//data的总长度
    private int numOfNow;//已经完成的长度

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_recommendation, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        queue = VolleySingleton.getInstance(getActivity()).getRequestQueue();
        handler = new Handler();
        mContext = getActivity();
        viewPager = (ViewPager) view.findViewById(R.id.handpickViewPager);
        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.plaza.getFocusPic&format=json&num=6";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    Recommendation result = gson.fromJson(response, Recommendation.class);
                    if (result != null) {
                        datas = result.getPic();
                        Log.i("djjf", datas + "");
                        adapter = new ViewPagerAdapter(getActivity(), datas);
                        viewPager.setAdapter(adapter);
                        getinit();
                        //设置第一张图片的位置
                        viewPager.setCurrentItem(10000);
                        initRunnable(datas.size());
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
        //初始化容器
        init();
        initNew();//最新歌曲
        initGride();//歌单推荐
        initList();//热门歌曲推荐

    }
    private void initNew() {
        newRecomTextView = (TextView) view.findViewById(R.id.newRecomTextView);
        newRecomText = (TextView) view.findViewById(R.id.newRecomText);
        newMore = (TextView) view.findViewById(R.id.newMore);
        newMore.setOnClickListener(this);
        newRecomGrideView = (ImageView) view.findViewById(R.id.newRecomGrideView);
        newNoScrollGridView = (NoScrollGridView) view.findViewById(R.id.newNoScrollGridView);
        newAdapter = new RecomNewAdapter(getActivity());
        newNoScrollGridView.setAdapter(newAdapter);
        newNoScrollGridView.setOnItemClickListener(this);
        newRecomGrideView.setOnClickListener(this);
        String urlG = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.plaza.getRecommendAlbum&format=json&offset=0&limit=2";
        StringRequest stringRequest = new StringRequest(urlG, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    NewGride result = gson.fromJson(response, NewGride.class);
                    dataN = result.getPlaze_album_list().getRM().getAlbum_list().getList();
                    newAdapter.initData(dataN);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(stringRequest);
        String urlnew = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.diy.getFirstPublish&format=json";
        StringRequest request = new StringRequest(urlnew, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    NewImageView result = gson.fromJson(response, NewImageView.class);
                    if (result != null) {
                        dataI = result.getCollection();
                        try {

                            Picasso.with(getActivity()).load(dataI.getPic()).into(newRecomGrideView);
                        } catch (Exception e) {
                        }
                        String URL = dataI.getPic();
                        Picasso.with(mContext).load(URL).into(newRecomGrideView);
                        newRecomTextView.setText(dataI.getTitle());
                        newRecomText.setText(dataI.getMessage());
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }

    private void initList() {
        listView = (NoScrollListView) view.findViewById(R.id.recommendListView);
        listAdapter = new RecomListAdapter(getActivity());
        listView.setAdapter(listAdapter);
        String urltwo = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getEditorRecommend&format=json&num=6";
        StringRequest requestList = new StringRequest(urltwo, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    RecomList recomList = gson.fromJson(response, RecomList.class);
                    if (recomList != null) {
                        dataone = recomList.getContent().get(0).getSong_list();
                        listAdapter.initData(dataone);
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(requestList);
        //对listview进行监听 播放歌曲
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                getAllUrl(position);
            }
        });
    }
    private void getAllUrl(int position) {
        clickPosition = position;//记录下当前点击的position
        numOfData = dataone.size();//设置总长度
        numOfNow = 0;//设置当前完成的长度
        for (int i = 0; i < datas.size(); i++) {//获得所有的Url进行网络数据的拉取
            String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                    dataone.get(i).getSong_id() + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                    "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
            getInternetData(url, i);//i记录了当前正在解析哪个URL
            //让data集合拥有跟数据匹配的长度
            PlayMusicEntity playMusicEntity = new PlayMusicEntity();
            dataP.add(playMusicEntity);
        }

    }
    //网络解析
    private void getInternetData(String url, final int position) {
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {//成功回调
                //进行解析
                NewSongListEntity entity = JSON.parseObject(s, NewSongListEntity.class);
                if (entity != null) {//解析成功,这是其中一个音乐的播放地址
                    String url = entity.getSongurl().getUrl().get(0).getShow_link();//获得了URL
                    String pic = dataone.get(position).getPic_big();
                    String singerName = dataone.get(position).getAuthor();
                    String songName = dataone.get(position).getTitle();
                    //设置data的相应位置的数据
                    dataP.get(position).setUrl(url);
                    dataP.get(position).setPicUrl(pic);
                    dataP.get(position).setSingerName(singerName);
                    dataP.get(position).setSongName(songName);
                    numOfNow++;
                    if (numOfNow >= numOfData) {
                        //所有数据均已加载完成
                        EventBus.getDefault().post(new MyEvent.PassData(dataP, clickPosition));
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                numOfNow++;
                Log.i("NewSongListFragment", "当前已完成" + numOfNow);

            }
        });
        queue.add(request);
    }

    private void initGride() {
        recomTextView = (TextView) view.findViewById(R.id.recomTextView);
        recomTextView.setOnClickListener(this);
        gridView = (NoScrollGridView) view.findViewById(R.id.recommendGridView);

        grideAdapter = new RecomGrideAdapter(getActivity());
        gridView.setAdapter(grideAdapter);
        String urlone = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.diy.getHotGeDanAndOfficial&format=json&num=6";
        StringRequest string = new StringRequest(urlone, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    Gson gson = new Gson();
                    RecomGride result = gson.fromJson(response, RecomGride.class);
                    if (result != null) {
                        data = result.getContent().getList();
                        grideAdapter.iniData(data);
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(string);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MenuItemFragment fragment = new MenuItemFragment();
                Bundle bundle = new Bundle();
                String b = data.get(position).getListid();
                String url = data.get(position).getPic();
                String time = data.get(position).getTitle();
                bundle.putString("id", b);
                bundle.putString("url", url);
                bundle.putString("time", time);
                fragment.setArguments(bundle);
                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, fragment)
                        .commit();
            }
        });
    }

    //开始轮播
    private void initRunnable(int size) {
        runnable = new Runnable() {
            @Override
            public void run() {
                int index = viewPager.getCurrentItem();
                viewPager.setCurrentItem(++index);
                if (flag) {
                    handler.postDelayed(runnable, Time);
                }
            }
        };
        if (flag) {
            handler.postDelayed(runnable, Time);
        }

    }

    private void init() {
        viewPager.addOnPageChangeListener(this);
        linearLayout = (LinearLayout) view.findViewById(R.id.viewPicture);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        try {

            for (int i = 0; i < datas.size(); i++) {
                ImageView imageView = (ImageView) linearLayout.getChildAt(i);
                imageView.setImageResource(R.mipmap.point_white);

            }
            if (datas != null && datas.size() > 0) {
                ImageView imageView = (ImageView) linearLayout.getChildAt(position % datas.size());
                imageView.setImageResource(R.mipmap.buttongreen);
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void getinit() {
        for (int i = 0; i < datas.size(); i++) {
            ImageView imageView = new ImageView(view.getContext());
            //对点位置设置
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(25, 25);
            imageView.setPadding(1, 7, 8, 7);
            imageView.setLayoutParams(params);
            if (i == 0) {
                imageView.setImageResource(R.mipmap.buttongreen);
            } else {
                imageView.setImageResource(R.mipmap.point_white);
            }
            linearLayout.addView(imageView);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        flag = true;
        handler.post(runnable);
    }

    @Override
    public void onStop() {
        super.onStop();
        flag = false;
        handler.removeCallbacks(runnable);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.recomTextView:
                int a = 1;
                EventBus.getDefault().post(new MyEvent.Recommend(a));

                break;
            case R.id.newRecomGrideView:
                //最新歌曲左边
                leftFragment = new NewLeftFragment();
                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, leftFragment)
                        .commit();
                Bundle bundle = new Bundle();
                String id = dataI.getList_id();
                String url = dataI.getPic();
                bundle.putString("id", id);
                bundle.putString("url", url);
                leftFragment.setArguments(bundle);
                break;
            case R.id.newMore:
                //最新歌曲推荐更多
                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, new MoreFragment())
                        .commit();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        rightFragment = new NewRightFragment();
        getFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.container, rightFragment)
                .commit();
        Bundle bundle = new Bundle();
        String index = dataN.get(position).getAlbum_id();
        String url = dataN.get(position).getPic_radio();
        bundle.putString("id", index);
        bundle.putString("url", url);
        rightFragment.setArguments(bundle);
    }
}
